package com.itheima.reggie.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.Mapper.DishMapper;
import com.itheima.reggie.Pojo.Dish;
import com.itheima.reggie.Pojo.DishFlavor;
import com.itheima.reggie.Service.DishFlavorService;
import com.itheima.reggie.Service.DishService;
import com.itheima.reggie.dto.DishDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
                             implements DishService {


    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品
     * @param dishDto
     */
    @Override
    public void saveDish_flavor(DishDto dishDto) {
//      新建菜品
        this.save(dishDto);
//      获取当前菜品的Id
        Long id = dishDto.getId();
//      获取菜品口味的list集合，list集合中只封装了口味名称跟值，没有包含关联菜品的id
        List<DishFlavor> flavors = dishDto.getFlavors();
//      list集合中因为没有包含关联菜品的id，所以需要手动给口味关联菜品id(关联当前菜品的id)，
//      关联菜品的id是不能为空的，所以这一步是必要的
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }
//      批量新增菜品口味
        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 根据id回显菜品数据(包含口味数据)
     * @param id
     * @return
     */
    @Override
    public DishDto getdish_flavor(Long id) {
//      创建dish对象
        Dish dish = this.getById(id);
//      创建dishDto对象
        DishDto dishDto=new DishDto();
//      dishflavor条件构造器
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
//      根据dishid查询
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
//      拷贝dish的内容到dishDto去
        BeanUtils.copyProperties(dish,dishDto);
//      单独再赋值flasvors
        dishDto.setFlavors(list);
        return dishDto;
    }

    /**
     * 修改菜品
     * @param dishDto
     */
    @Override
    public void updateDish_flavor(DishDto dishDto) {
//      修改菜品
        this.updateById(dishDto);
//      获取修改后的菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
//      删除掉当前菜品的口味记录
        dishFlavorService.remove(queryWrapper);
//      给flavors设置Dishid的值
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
//      批量新增口味数据
        dishFlavorService.saveBatch(flavors);

    }


}
